#include "base/logging.h"
#include "shop_waiter_del_request.h"

#include <iostream>
#include <sstream>
#include <string>
#include <map>

#include "base/json_escape.h"
#include "base/config_reader.h"
#include "database/scoped_connection.h"
#include "database/simple_db_pool.h"

namespace imserver {
namespace fcgi {


extern ConfigReader g_config;

bool ShopWaiterDelRequest::Response() {
  if (!fcgi_out_) {
    LOG_WARN("null fcgi_out!");
    return false;
  }

  int64_t shop_id = 0;
  try {
    shop_id = boost::lexical_cast<int64_t>(GetQuery("s"));
  } catch (boost::bad_lexical_cast&) {}

  int64_t waiter_id = 0;
  try {
    waiter_id = boost::lexical_cast<int64_t>(GetQuery("w"));
  } catch (boost::bad_lexical_cast&) {}

  if (shop_id <= 0 || waiter_id <= 0 || shop_id == waiter_id) {
    std::stringstream rsp;
    rsp << "Content-type: text/plain; charset=utf-8\r\n" << "\r\nbad-parameters";
    FCGX_PutS(rsp.str().c_str(), fcgi_out_);
    return false;
  }

  base::SimpleConnectionPool db_conn_pool(g_config.Get("database", "name").c_str(),
                      g_config.Get("database", "server_list").c_str(),
                      g_config.Get("database", "user").c_str(),
                      g_config.Get("database", "password").c_str());

  mysqlpp::ScopedConnection db(db_conn_pool);
  if (!db) {
    LOG_ERROR("CallCenterCache::Reload failed to get a connection from database-pool.");
    return false;
  }

  mysqlpp::Query query(db->query());
  query << "DELETE FROM shop_waiters WHERE shop=" << shop_id << " AND waiter=" << waiter_id;

  int code = 0;
  try {
    query.exec();
  } catch (mysqlpp::Exception& e) {
    LOG_ERROR("ShopWaiterMap::Reload " << query.str() << " EXEC ERROR.(" << e.what() << ")");
    code = 1;
  }

  std::stringstream rsp;
  rsp << "Content-type: text/javascript; charset=utf-8\r\n" << "\r\n" << code;
  FCGX_PutS(rsp.str().c_str(), fcgi_out_);
  return true;
}

}
}


